<template>
  <div class="register-form">
    <h2 class="form-title">律师注册</h2>
    <el-form :model="form" :rules="rules" ref="registerFormRef">
      <el-form-item prop="username">
        <el-input 
          v-model="form.username" 
          placeholder="用户名" 
          :prefix-icon="User"
          size="large"
        />
      </el-form-item>
      
      <el-form-item prop="password">
        <el-input 
          v-model="form.password" 
          type="password" 
          placeholder="密码" 
          :prefix-icon="Lock"
          size="large"
          show-password
        />
      </el-form-item>
      
      <el-form-item prop="confirmPassword">
        <el-input 
          v-model="form.confirmPassword" 
          type="password" 
          placeholder="确认密码" 
          :prefix-icon="Lock"
          size="large"
          show-password
        />
      </el-form-item>
      
      <el-form-item prop="phone">
        <el-input 
          v-model="form.phone" 
          placeholder="手机号" 
          :prefix-icon="Iphone"
          size="large"
        />
      </el-form-item>
      
      <el-form-item prop="email">
        <el-input 
          v-model="form.email" 
          placeholder="邮箱" 
          :prefix-icon="Message"
          size="large"
        />
      </el-form-item>
      
      <el-form-item prop="realName">
        <el-input 
          v-model="form.realName" 
          placeholder="真实姓名" 
          :prefix-icon="Edit"
          size="large"
        />
      </el-form-item>
      
      <el-form-item prop="idCard">
        <el-input 
          v-model="form.idCard" 
          placeholder="身份证号" 
          :prefix-icon="CreditCard"
          size="large"
        />
      </el-form-item>
      
      <el-form-item prop="lawyerLicense">
        <el-input 
          v-model="form.licenseNo"
          placeholder="律师执业证号"
          :prefix-icon="Document"
          size="large"
        />
      </el-form-item>
      <!-- 补充专业领域 -->
      <el-form-item prop="specialty">
        <el-input
            v-model="form.specialty"
            placeholder="专业领域（如：民事诉讼、刑事辩护）"
            :prefix-icon="Book"
            size="large"
        />
      </el-form-item>

      <!-- 补充执业年限 -->
      <el-form-item prop="yearsOfPractice">
        <el-input
            v-model.number="form.yearsOfPractice"
            type="number"
            placeholder="执业年限（请输入正数）"
            :prefix-icon="Calendar"
            size="large"
            min="1"
        />
      </el-form-item>

      <!-- 补充服务区域 -->
      <el-form-item prop="serviceArea">
        <el-input
            v-model="form.serviceArea"
            placeholder="服务区域（如：北京市朝阳区）"
            :prefix-icon="Location"
            size="large"
        />
      </el-form-item>

      <!-- 补充个人简介 -->
      <el-form-item prop="introduction">
        <el-input
            v-model="form.introduction"
            type="textarea"
            placeholder="个人简介（可选）"
            :rows="4"
        />
      </el-form-item>
      <el-form-item prop="avatar">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :auto-upload="false"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">点击上传头像</div>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          size="large" 
          @click="submitForm"
          style="width: 100%"
        >
          注册
        </el-button>
      </el-form-item>
      
      <div class="form-footer">
        <el-link type="primary" @click="emit('switch-form', 'LoginForm')">
          返回登录
        </el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { UserApi } from '@/api/user'
import {
  User, Lock, Iphone, Message, Edit, CreditCard, Document, Plus, Calendar
} from '@element-plus/icons-vue'

const emit = defineEmits(['switch-form', 'register-success'])

const registerFormRef = ref(null)

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  realName: '',
  idCard: '',
  licenseNo: '',
  avatar: '',
  specialty: '',
  yearsOfPractice: null,
  serviceArea: '',
  introduction: ''
})

const validatePass2 = (rule, value, callback) => {
  if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validateIdCard = (rule, value, callback) => {
  const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if (!value) {
    callback(new Error('请输入身份证号'))
  } else if (!idCardReg.test(value)) {
    callback(new Error('请输入正确的身份证号'))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  idCard: [
    { validator: validateIdCard, trigger: 'blur' }
  ],
  licenseNo: [
    { required: true, message: '请输入律师执业证号', trigger: 'blur' }
  ],
  specialty: [
    { required: true, message: '请输入专业领域', trigger: 'blur' }
  ],
  yearsOfPractice: [
    { required: true, message: '请输入执业年限', trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      message: '执业年限必须为正数',
      trigger: 'blur',
      // 添加转换函数，确保值被当作数字处理
      transform(value) {
        return Number(value);
      }
    }
  ],
  serviceArea: [
    { required: true, message: '请输入服务区域', trigger: 'blur' }
  ],
})

const handleAvatarChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatar = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const submitForm = async () => {
  try {
    await registerFormRef.value.validate()
    await UserApi.registerLawyer(form)
    ElMessage.success('注册成功')
    emit('switch-form', 'LoginForm');
  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error('注册失败，请检查输入信息');
  }
}
</script>

<style scoped>
.register-form {
  position: relative;
  z-index: 1;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: 600;
  font-size: 24px;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
}

.upload-tip {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>